import { defineStore } from 'pinia'

/**
 * 创建通用 store
 * @param {string} name store 名称
 * @param {Object} options 配置项
 * @param {Object} options.state 初始状态
 * @param {Object} options.persist 持久化配置 { enable: boolean, keys: string[] }
 * @returns {Object} store 实例
 */
export function createStore(name, options = {}) {
  const { state = {}, persist = { enable: false, keys: [] } } = options

  // 从本地存储恢复状态
  const initialState = { ...state }
  if (persist.enable) {
    persist.keys.forEach(key => {
      const value = uni.getStorageSync(`${name}_${key}`)
      if (value !== '') {
        initialState[key] = value
      }
    })
  }

  return defineStore(name, {
    state: () => initialState,
    actions: {
      // 设置单个值
      setValue(key, value) {
        if (key in this.$state) {
          this[key] = value
          // 如果需要持久化，则保存到本地存储
          if (persist.enable && persist.keys.includes(key)) {
            uni.setStorageSync(`${name}_${key}`, value)
          }
        }
      },
      // 批量设置值
      setValues(values) {
        Object.entries(values).forEach(([key, value]) => {
          this.setValue(key, value)
        })
      },
      // 重置状态
      resetState() {
        Object.keys(state).forEach(key => {
          this[key] = state[key]
          if (persist.enable && persist.keys.includes(key)) {
            uni.removeStorageSync(`${name}_${key}`)
          }
        })
      },
      // 清除持久化数据
      clearPersist() {
        if (persist.enable) {
          persist.keys.forEach(key => {
            uni.removeStorageSync(`${name}_${key}`)
          })
        }
      }
    }
  })
}